package edu.ccut.saturn.manager.bundles.core;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.osgi.framework.Bundle;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.core.ServiceFactory;

public class GetRelease extends DefaultComponent {
	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		List<Map> list = (List<Map>) parameterContext.getParameterValue(0);

		byte[] bundleFile = (byte[]) list.get(0).get("content");

		parameterContext.setParameter(1, bundleFile);

		String location = getLocation().substring(5);

		parameterContext.setParameter(2, location);

		parameterContext.setParameter(3, location + "\\"
				+ list.get(0).get("name"));

		parameterContext.setParameter(4, list.get(0).get("name"));
	}

	private String getLocation() {
		String location = null;
		String releasePath = "";

		Bundle[] bundles = ServiceFactory.getBundleService().getBundles();

		for (Bundle bundle : bundles) {
			String bundlelocation = bundle.getLocation();
			int lastSlash = bundlelocation.lastIndexOf("bundles");
			if (lastSlash != -1) {
				releasePath = bundlelocation.substring(0, lastSlash + 7);
				break;
			}
		}

		location = releasePath + "\\plugins";
		return location;
	}

	/*
	 * private String getLocation() { String releasePath = ""; Bundle[] bundles =
	 * ServiceFactory.getBundleService().getBundles();
	 * 
	 * for(Bundle bundle :bundles) { String bundlelocation =
	 * bundle.getLocation();
	 * 
	 * int lastSlash = bundlelocation.lastIndexOf(File.separator);
	 * 
	 * if(lastSlash != -1) { String str =
	 * bundlelocation.substring(lastSlash-7,lastSlash);
	 * 
	 * if(str.equals("plugins")) { releasePath =
	 * bundlelocation.substring(0,lastSlash); break; } } }
	 * 
	 * return releasePath; }
	 */
}